package com.hyt.it.ogt.ykcj.service.analysis.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyt.it.ogt.ykcj.common.constant.HttpStatus;
import com.hyt.it.ogt.ykcj.common.core.page.PageDomain;
import com.hyt.it.ogt.ykcj.common.core.page.TableDataInfo;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.ExamFormEnums;
import com.hyt.it.ogt.ykcj.common.exception.CustomException;
import com.hyt.it.ogt.ykcj.common.utils.DateUtils;
import com.hyt.it.ogt.ykcj.domain.analysis.ExamScoreAnalysisBlockLine;
import com.hyt.it.ogt.ykcj.domain.analysis.ExamScoreAnalysisLine;
import com.hyt.it.ogt.ykcj.domain.exam.EnterpriseExamScoreLineSetting;
import com.hyt.it.ogt.ykcj.domain.exam.ExamInfo;
import com.hyt.it.ogt.ykcj.domain.exam.ExamNameConfig;
import com.hyt.it.ogt.ykcj.domain.exam.ExamSubjectInfo;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.param.EnterpriseScoreLineSaveParam;
import com.hyt.it.ogt.ykcj.domain.vo.*;
import com.hyt.it.ogt.ykcj.domain.vo.analysis.*;
import com.hyt.it.ogt.ykcj.feign.model.Classification;
import com.hyt.it.ogt.ykcj.feign.model.TaskCandidateAreaVO;
import com.hyt.it.ogt.ykcj.mapper.analysis.ExamScoreAnalysisBlockLineLMapper;
import com.hyt.it.ogt.ykcj.mapper.analysis.ExamScoreAnalysisLineLMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.*;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeSubjectGradeMapper;
import com.hyt.it.ogt.ykcj.service.analysis.IEnterpriseExamineeAnalysisDataService;
import com.hyt.it.ogt.ykcj.service.exam.IClassificationService;
import com.hyt.it.ogt.ykcj.service.exam.IEnterpriseExamScoreLineSettingService;
import com.hyt.it.ogt.ykcj.service.exchange.IAreaService;
import com.hyt.it.ogt.ykcj.service.system.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * description
 * 学生归档信息service
 *
 * @author yaojian
 * @createTime 2021/12/27
 */
@Slf4j
@Service
public class EnterpriseExamineeAnalysisDataServiceImpl implements IEnterpriseExamineeAnalysisDataService {

    @Autowired
    private ExamInfoMapper examInfoMapper;
    @Autowired
    private ExamSubjectInfoMapper examSubjectInfoMapper;

    @Autowired
    private ExamNameConfigMapper examNameConfigMapper;

    @Autowired
    private EnterpriseExamScoreLineSettingMapper enterpriseExamScoreLineSettingMapper;
    @Autowired
    private EnterpriseExamScoreLineSettingSubMapper enterpriseExamScoreLineSettingSubMapper;
    @Autowired
    private ExamScoreAnalysisBlockLineLMapper examScoreAnalysisBlockLineLMapper;
    @Autowired
    private ExamScoreAnalysisLineLMapper examScoreAnalysisLineLMapper;
    @Autowired
    private IEnterpriseExamScoreLineSettingService enterpriseExamScoreLineSettingService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private IAreaService areaService;
    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private EnterpriseExamineeSubjectGradeMapper enterpriseExamineeSubjectGradeMapper;

    @Autowired
    private EnterpriseExamineeInfoMapper enterpriseExamineeInfoMapper;



    @Override
    public ExamScoreAnalysisVo selectTotalAnalysisById(AnalysisVo analysisVo) {

        ExamInfoVo examInfoVo = examInfoMapper.selectExamInfoByExamId(analysisVo.getExamId());
        if (examInfoVo == null || StringUtils.isEmpty(examInfoVo.getId())) {
            return  null;
        }
        //考试组
        if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examInfoVo.getExamForm())){
            //关联考试

            List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
            if(CollectionUtils.isNotEmpty(examInfoVos) && examInfoVos.size()>1){
                return groupExamScoreAnalysisVo(examInfoVos,examInfoVo,analysisVo);
            }else {
                return commonExamScoreAnalysisVo(examInfoVo,analysisVo);
            }
        }else{
            return commonExamScoreAnalysisVo(examInfoVo,analysisVo);
        }
     }

    /**
     * 考试组（关联考试）
     * @param examInfoVo
     * @param analysisVo
     * @return
     */
    private ExamScoreAnalysisVo groupExamScoreAnalysisVo(List<ExamInfoVo> examInfoVos,ExamInfoVo examInfoVo,AnalysisVo analysisVo){
        ExamScoreAnalysisVo examScoreAnalysisVo = new ExamScoreAnalysisVo();
        // 获取考试类型，然后拼接
        examScoreAnalysisVo.setExamType(getTypeNameById(examInfoVo.getExamType()));
        //考试组
        examScoreAnalysisVo.setExamForm(examInfoVo.getExamForm());
        examScoreAnalysisVo.setSignNumber(examInfoVo.getSignNumber());
        examScoreAnalysisVo.setStartTime(examInfoVo.getExamStartDay());
        examScoreAnalysisVo.setEndTime(examInfoVo.getExamEndDay());
        //设置答题时间
        if (examInfoVo.getUseTime() != null) {
            examScoreAnalysisVo.setUseTimeStr( DateUtils.getTimeStrNoSingn(examInfoVo.getUseTime()) + "分钟");
        } else {
            examScoreAnalysisVo.setUseTimeStr("不限");
        }
        //计算平均分的时间 默认值
        examScoreAnalysisVo.setAvgTimeStr("--");
        //查询子考试的科目
        List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
        List<ExamSubjectVo> examSubjectVos =  examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds.toArray(new String[examIds.size()]));
        if (CollectionUtils.isNotEmpty(examSubjectVos)) {
            examScoreAnalysisVo.setSubjectCount(examSubjectVos.size());
        } else {
            examScoreAnalysisVo.setSubjectCount(0);
        }
        //获取试卷的总分
        BigDecimal totalScore =examSubjectVos.stream().filter(e->null != e.getPaperFullMarks()).map(ExamSubjectVo::getPaperFullMarks).reduce(BigDecimal.ZERO, BigDecimal::add);
        examScoreAnalysisVo.setTotalScore(totalScore);
        //获取考试中考生的总成绩信息
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getGroupEnterpriseExamineeInfos(examIds,analysisVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  examScoreAnalysisVo;
        }
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getGroupEnterpriseExamineeSubjectGradeVos(examIds,enterpriseExamineeInfos,null);
        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  examScoreAnalysisVo;
        }

        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));
        for(EnterpriseExamineeInfo examineeInfo : enterpriseExamineeInfos){
            if(MapUtils.isEmpty(subjectGradeMap) || CollectionUtils.isEmpty(subjectGradeMap.get(examineeInfo.getId())) ){
                examineeInfo.setAllScore(BigDecimal.ZERO);
                continue;
            }
            examineeInfo.setAllScore(subjectGradeMap.get(examineeInfo.getId()).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
        }

        //设置参考人数
        examScoreAnalysisVo.setParticipateCount(enterpriseExamineeInfos.size());
        //应考人数
        if(CommonEnums.ORIGIN_1.getCode().equals(examInfoVo.getOrigin())){
            examScoreAnalysisVo.setSignNumber(examInfoVo.getSignNumber());
        }else {
            examScoreAnalysisVo.setSignNumber(null);
        }
        //缺考率=（应考人数-参考人数）/应考人数*100%
        examScoreAnalysisVo.setSignProportion(null);
        if(examInfoVo.getSignNumber()-enterpriseExamineeInfos.size() > 0){
            examScoreAnalysisVo.setSignProportion(new BigDecimal(examInfoVo.getSignNumber()-enterpriseExamineeInfos.size())
                    .multiply(new BigDecimal(100)).divide(new BigDecimal(examInfoVo.getSignNumber()),2,BigDecimal.ROUND_HALF_UP));
        }

        Map<String,List<EnterpriseExamineeInfo>> tempExamineeInfoMap = enterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getIdcard()+c.getName()));
        List<EnterpriseExamineeInfo> distEnterpriseExamineeInfos = new ArrayList<>(tempExamineeInfoMap.size());
        for (String tempKey :tempExamineeInfoMap.keySet()) {
            List<EnterpriseExamineeInfo> examineeInfos = tempExamineeInfoMap.get(tempKey);
            EnterpriseExamineeInfo examineeInfo = examineeInfos.get(0);
            BigDecimal  score =  examineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            examineeInfo.setAllScore(score);
            distEnterpriseExamineeInfos.add(examineeInfo);
        }

        //设置平均分，设置最高分，设置最低分
        BigDecimal maxScore = distEnterpriseExamineeInfos.stream().max(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();
        BigDecimal minScore = distEnterpriseExamineeInfos.stream().min(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();

        BigDecimal allScore = enterpriseExamineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal allUserTime = new BigDecimal(enterpriseExamineeInfos.stream().filter(e->null != e.getUseTime()).mapToLong(EnterpriseExamineeInfo::getUseTime).sum());
        examScoreAnalysisVo.setAvgScore(allScore.divide(new BigDecimal(enterpriseExamineeInfos.size()),2, BigDecimal.ROUND_HALF_UP) );
        examScoreAnalysisVo.setMaxScore(maxScore);
        examScoreAnalysisVo.setMixScore(minScore);
        Long avgTime = allUserTime.divide(new BigDecimal(enterpriseExamineeInfos.size()),2, BigDecimal.ROUND_HALF_UP).longValue();
        BigDecimal minTimeStr =  DateUtils.getMinTimeStr(avgTime);
        examScoreAnalysisVo.setAvgTime(minTimeStr);
        //合格率
        //没有设置，不需要任何处理
        examScoreAnalysisVo.setExist(CommonEnums.EXIST_COMPOSITE_0.getCode());
        //设置考试的分数线
        List<EnterpriseScoreLineSaveParam> scoreLineList = enterpriseExamScoreLineSettingService.getScoreLineList(analysisVo.getExamId(), CommonEnums.SCORE_LINE_DIMENSION_2.getCode(), null);
        if (CollectionUtils.isNotEmpty(scoreLineList)) {
            getScoreLineList(examScoreAnalysisVo,scoreLineList,enterpriseExamineeInfos,ExamFormEnums.FORM_EXAM_GROUP.getCode());
            examScoreAnalysisVo.setScoreLineList(scoreLineList);
        }

        //计算平均分的时间
        if (examScoreAnalysisVo.getAvgTime() != null) {
            examScoreAnalysisVo.setAvgTimeStr( DateUtils.getTimeStr(avgTime));
        }

        return examScoreAnalysisVo;
    }

    /**
     * 普通考试信息
     * @param examInfoVo
     * @param analysisVo
     * @return
     */
    private ExamScoreAnalysisVo commonExamScoreAnalysisVo(ExamInfoVo examInfoVo,AnalysisVo analysisVo){
        ExamScoreAnalysisVo examScoreAnalysisVo = new ExamScoreAnalysisVo();
        //获取考试科目
        // 获取考试类型，然后拼接
        examScoreAnalysisVo.setExamType(getTypeNameById(examInfoVo.getExamType()));
        examScoreAnalysisVo.setSignNumber(examInfoVo.getSignNumber());
        //考试组
        examScoreAnalysisVo.setExamForm(examInfoVo.getExamForm());
        examScoreAnalysisVo.setStartTime(examInfoVo.getExamStartDay());
        examScoreAnalysisVo.setEndTime(examInfoVo.getExamEndDay());
        if (examInfoVo.getSubjectVos() != null) {
            examScoreAnalysisVo.setSubjectCount(examInfoVo.getSubjectVos().size());
        } else {
            examScoreAnalysisVo.setSubjectCount(0);
        }
        //获取试卷的总分
        BigDecimal totalScore = examInfoVo.getSubjectVos().stream().filter(e->null != e.getPaperFullMarks()).map(ExamSubjectVo::getPaperFullMarks).reduce(BigDecimal.ZERO, BigDecimal::add);
        examScoreAnalysisVo.setTotalScore(totalScore);
        //获取考试中考生的总成绩信息
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getCommonEnterpriseExamineeInfos(analysisVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  examScoreAnalysisVo;
        }
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getCommonEnterpriseExamineeSubjectGradeVos(analysisVo.getExamId(),enterpriseExamineeInfos);
        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  examScoreAnalysisVo;
        }
        //设置考试的分数线
        List<EnterpriseScoreLineSaveParam> scoreLineList = enterpriseExamScoreLineSettingService.getScoreLineList(analysisVo.getExamId(), CommonEnums.SCORE_LINE_DIMENSION_0.getCode(), null);
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));
        for(EnterpriseExamineeInfo examineeInfo : enterpriseExamineeInfos){
            if(MapUtils.isEmpty(subjectGradeMap) || CollectionUtils.isEmpty(subjectGradeMap.get(examineeInfo.getId())) ){
                examineeInfo.setAllScore(BigDecimal.ZERO);
                continue;
            }
            examineeInfo.setAllScore(subjectGradeMap.get(examineeInfo.getId()).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
        }

        //设置参考人数
        examScoreAnalysisVo.setParticipateCount(enterpriseExamineeInfos.size());
        //应考人数
        if(CommonEnums.ORIGIN_1.getCode().equals(examInfoVo.getOrigin())){
            examScoreAnalysisVo.setSignNumber(examInfoVo.getSignNumber());
        }else {
            examScoreAnalysisVo.setSignNumber(null);
        }
        //缺考率=（应考人数-参考人数）/应考人数*100%
        if(examInfoVo.getSignNumber()-enterpriseExamineeInfos.size() > 0){
            examScoreAnalysisVo.setSignProportion(new BigDecimal(examInfoVo.getSignNumber()-enterpriseExamineeInfos.size())
                    .multiply(new BigDecimal(100)).divide(new BigDecimal(examInfoVo.getSignNumber()),2,BigDecimal.ROUND_HALF_UP));
        }
        if(CommonEnums.ORIGIN_0.getCode().equals(examInfoVo.getOrigin())){
            examScoreAnalysisVo.setSignProportion(null);
        }
        //设置平均分，设置最高分，设置最低分
        BigDecimal maxScore = enterpriseExamineeInfos.stream().max(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();
        BigDecimal minScore = enterpriseExamineeInfos.stream().min(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();

        BigDecimal allScore = enterpriseExamineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal allUserTime = new BigDecimal(enterpriseExamineeInfos.stream().filter(e->null != e.getUseTime()).mapToLong(EnterpriseExamineeInfo::getUseTime).sum());
        examScoreAnalysisVo.setAvgScore(allScore.divide(new BigDecimal(enterpriseExamineeInfos.size()),2, BigDecimal.ROUND_HALF_UP) );
        examScoreAnalysisVo.setMaxScore(maxScore);
        examScoreAnalysisVo.setMixScore(minScore);
        BigDecimal avgTime = allUserTime.divide(new BigDecimal(enterpriseExamineeInfos.size()),2, BigDecimal.ROUND_HALF_UP);
        examScoreAnalysisVo.setAvgTime(avgTime );
        //合格率
        //没有设置，不需要任何处理
        examScoreAnalysisVo.setExist(CommonEnums.EXIST_COMPOSITE_0.getCode());
        if (CollectionUtils.isNotEmpty(scoreLineList)) {
            getScoreLineList(examScoreAnalysisVo,scoreLineList,enterpriseExamineeInfos,ExamFormEnums.FORM_EXAM.getCode());
            examScoreAnalysisVo.setScoreLineList(scoreLineList);
        }
        //设置答题时间
        if (examInfoVo.getUseTime() != null) {

            examScoreAnalysisVo.setUseTimeStr( DateUtils.getTimeStr(examInfoVo.getUseTime()));
        } else {
            examScoreAnalysisVo.setUseTimeStr("不限");
        }
        //计算平均分的时间
        if (examScoreAnalysisVo.getAvgTime() != null) {
            examScoreAnalysisVo.setAvgTimeStr( DateUtils.getTimeStr(avgTime.longValue()));
        } else {
            examScoreAnalysisVo.setAvgTimeStr("--");
        }

        return examScoreAnalysisVo;
    }

    private  void getScoreLineList(ExamScoreAnalysisVo examScoreAnalysisVo,List<EnterpriseScoreLineSaveParam> scoreLineList,List<EnterpriseExamineeInfo> enterpriseExamineeInfos,Integer examForm){
        //区间
        if(scoreLineList.get(0).getType().equals(CommonEnums.SCORE_LINE_TYPE_2.getCode())){
            examScoreAnalysisVo.setExist(CommonEnums.EXIST_COMPOSITE_2.getCode());

            Map<String,List<EnterpriseExamineeInfo>> examineeRegionNameMap = null;
            if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examForm)){
                examineeRegionNameMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getGroupRegionName())).collect(Collectors.groupingBy(c -> c.getGroupRegionName()));
            }else {
                examineeRegionNameMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRegionName())).collect(Collectors.groupingBy(c -> c.getRegionName()));
            }
            for (EnterpriseScoreLineSaveParam enterpriseScoreLineSaveParam : scoreLineList) {
                enterpriseScoreLineSaveParam.setProportion(null);
                if(CollectionUtils.isNotEmpty(examineeRegionNameMap.get(enterpriseScoreLineSaveParam.getRegionName()))){
                    int qualifiedCount = examineeRegionNameMap.get(enterpriseScoreLineSaveParam.getRegionName()).size();
                    BigDecimal res = new BigDecimal(qualifiedCount).divide(new BigDecimal(enterpriseExamineeInfos.size()), 2, BigDecimal.ROUND_HALF_UP).movePointRight(2);
                    enterpriseScoreLineSaveParam.setProportion(res);
                }

            }
        }else {
            List<EnterpriseExamineeInfo> examineeInfos = null;
            if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examForm)){
                examineeInfos = enterpriseExamineeInfos.stream().filter(e->CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(e.getGroupQualifiedStatus())).collect(Collectors.toList());
            }else {
                examineeInfos = enterpriseExamineeInfos.stream().filter(e->CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(e.getQualifiedStatus())).collect(Collectors.toList());
            }
            examScoreAnalysisVo.setExist(CommonEnums.EXIST_COMPOSITE_1.getCode());
            examScoreAnalysisVo.setProportion(null);
            if(CollectionUtils.isNotEmpty(examineeInfos)){
                BigDecimal res = new BigDecimal(examineeInfos.size()).divide(new BigDecimal(enterpriseExamineeInfos.size()), 2, BigDecimal.ROUND_HALF_UP).movePointRight(2);
                examScoreAnalysisVo.setProportion(res);
            }
        }
    }

    /**
     * 获取类型名称
     *
     * @param typeId
     * @return
     */
    private String getTypeNameById(String typeId) {
        String typeName = "";
        String parentTypeId = "";
        List<Classification> classificationList = classificationService.getClassificationList();
        for (Classification classification : classificationList) {
            if (classification.getId().equals(typeId)) {
                parentTypeId = classification.getParentId();
                typeName = classification.getName();
                if (classification.getParentId().equals("0")) {
                    return typeName;
                }
            }
        }
        return getgetTypeNameByPid(parentTypeId, typeName, classificationList);
    }

    /**
     * 获取父的名称进行拼接
     */
    private String getgetTypeNameByPid(String parentTypeId, String typeName, List<Classification> classificationList) {
        //TODO 这里要考虑多级的情况
        for (Classification classification : classificationList) {
            if (classification.getExaminationId() != null && classification.getExaminationId().equals(parentTypeId)) {
                typeName = classification.getName() + "-" + typeName;
                break;
            }
        }
        return typeName;
    }






    private   List<BaseAnalysisVo> selectExportSubjectAnalysisList(AnalysisVo analysisVo)  {

        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){

            return getGroupSubjectBaseAnalysisVos(analysisVo,examInfoVos);

        }else {
            return getCommonSubjectBaseAnalysisVos(analysisVo);

        }

    }


    @Override
    public TableDataInfo selectSubjectAnalysisList(AnalysisVo analysisVo)  {

        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){

            List<BaseAnalysisVo> baseAnalysisVos = getGroupSubjectBaseAnalysisVos(analysisVo, examInfoVos);
            if(CollectionUtils.isEmpty(baseAnalysisVos)){
                return bulidTableDataInfo();
            }
            return resetDynamicColumnVoList(baseAnalysisVos);
        }else {
            List<BaseAnalysisVo> baseAnalysisVos = getCommonSubjectBaseAnalysisVos(analysisVo);
            if(CollectionUtils.isEmpty(baseAnalysisVos)){
                return bulidTableDataInfo();
            }
            return resetDynamicColumnVoList(baseAnalysisVos);
        }

    }

    private TableDataInfo bulidTableDataInfo(){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setHead(new ArrayList<>());
        rspData.setRows(new ArrayList<>());
        rspData.setAllRows(new ArrayList<>());
        rspData.setTotal(0);
        return rspData;
    }

    private TableDataInfo resetDynamicColumnVoList( List<BaseAnalysisVo> baseAnalysisVos) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");

        //设置动态头部
        List<Map> head = new ArrayList<>();
        //图形表中表示的数据都放在偶数上
        List<Map> allHead = new ArrayList<>();
        List<DynamicColumnVo> dynamicColumnVoList = baseAnalysisVos.get(0).getDynamicColumnVoList();
        for (int i = 0; i < dynamicColumnVoList.size(); i++) {
            Map dynamicMap = new HashMap<>();
            dynamicMap.put("lable", dynamicColumnVoList.get(i).getColumnName());
            dynamicMap.put("value", Integer.valueOf(i).toString());
            head.add(dynamicMap);
            if (i % 2 != 0) {
                allHead.add(dynamicMap);
            }
        }
        rspData.setHead(head);
        rspData.setAllHead(allHead);
        //设置动态头部对应的内容
        List<BaseAnalysisVo> allSubjectAnalysisVos = new ArrayList<>();
        for (BaseAnalysisVo baseAnalysisVo : baseAnalysisVos) {
            Map<Integer, Object> dynamicMap = new HashMap<>();
            Map<Integer, Object> allDynamicMap = new HashMap<>();
            BaseAnalysisVo tempBaseAnalysisVo = new BaseAnalysisVo();
            BeanUtils.copyProperties(baseAnalysisVo,tempBaseAnalysisVo);
            for (int i = 0; i < baseAnalysisVo.getDynamicColumnVoList().size(); i++) {
                if (i % 2 != 0) {
                    if (baseAnalysisVo.getDynamicColumnVoList().get(i).getColumnVal().equals("--")) {
                        allDynamicMap.put(i, "--");
                    } else {
                        allDynamicMap.put(i, new BigDecimal(baseAnalysisVo.getDynamicColumnVoList().get(i).getColumnVal()));
                    }

                }
                if (baseAnalysisVo.getDynamicColumnVoList().get(i).getColumnVal().equals("--")) {
                    dynamicMap.put(i, "--");
                } else {
                    dynamicMap.put(i, new BigDecimal(baseAnalysisVo.getDynamicColumnVoList().get(i).getColumnVal()));
                }


            }
            baseAnalysisVo.setDynamicColumnVoList(null);
            baseAnalysisVo.setDynamicList(dynamicMap);
            tempBaseAnalysisVo.setDynamicColumnVoList(null);
            tempBaseAnalysisVo.setDynamicList(allDynamicMap);
            allSubjectAnalysisVos.add(tempBaseAnalysisVo);
        }
        rspData.setRows(baseAnalysisVos);
        rspData.setAllRows(allSubjectAnalysisVos);

        return rspData;
    }

    /**
     * 考试组
     * @param analysisVo
     * @return
     */
    private List<BaseAnalysisVo> getGroupSubjectBaseAnalysisVos(AnalysisVo analysisVo,List<ExamInfoVo> examInfoVos){
        List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
        //复合条件的考生
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getGroupEnterpriseExamineeInfos(examIds,analysisVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  Collections.EMPTY_LIST;
        }
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getGroupEnterpriseExamineeSubjectGradeVos(examIds,enterpriseExamineeInfos,analysisVo.getSubjectId());
        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        //考生科目
        List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds.toArray(new String[examIds.size()]));
        List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos = null;
        if(StrUtil.isEmpty(analysisVo.getSubjectId())){
            scoreLineSettingSubVos = enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamId(
                    enterpriseExamineeSubjectGradeVos.get(0).getExamId(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }else{
            ExamSubjectInfo subjectInfo = examSubjectInfoMapper.selectExamSubjectInfoById(analysisVo.getSubjectId());
            scoreLineSettingSubVos = enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamIdAndSubjcetId(
                    subjectInfo.getExamInfoId(), analysisVo.getSubjectId(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }
        Map<String,String> subjectNameMap = examSubjectVos.stream().collect(Collectors.toMap(ExamSubjectVo::getSubjectId, ExamSubjectVo :: getSubjectName,(key1, key2)->key2));
        List<BaseAnalysisVo> baseAnalysisVoss = new ArrayList<>(enterpriseExamineeSubjectGradeVos.size());
        //按照科目分组
        Map<String,List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream()
                .filter(data -> ObjectUtil.isNotEmpty(data.getSubjectId()))
                .collect(Collectors.groupingBy(EnterpriseExamineeSubjectGradeVo::getSubjectId));
        for (String key :subjectGradeMap.keySet())  {
            baseAnalysisVoss.add(bulidSubjectBaseAnalysisVo(key,subjectNameMap,scoreLineSettingSubVos,subjectGradeMap,enterpriseExamineeSubjectGradeVos));
        }
        return   baseAnalysisVoss;
    }


    /**
     * 考试
     * @param analysisVo
     * @return
     */
    private List<BaseAnalysisVo> getCommonSubjectBaseAnalysisVos(AnalysisVo analysisVo){
        List<EnterpriseExamineeSubjectGradeVo>  enterpriseExamineeSubjectGradeVos = getEnterpriseExamineeSubjectGradeVos(analysisVo);
        List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectInfoByExamId(analysisVo.getExamId());
        List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos = new ArrayList<>();
        if(StrUtil.isEmpty(analysisVo.getSubjectId())) {
            scoreLineSettingSubVos = enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamId(
                    analysisVo.getExamId(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }else{
            scoreLineSettingSubVos = enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamIdAndSubjcetId(analysisVo.getExamId()
                    , analysisVo.getSubjectId(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode(),CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }
        if(StrUtil.isNotEmpty(analysisVo.getSubjectId())){
            examSubjectVos = examSubjectVos.stream().filter(item->item.getSubjectId().equals(analysisVo.getSubjectId())).collect(Collectors.toList());
            enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeVos.stream().filter(item->item.getSubjectId().equals(analysisVo.getSubjectId())).collect(Collectors.toList());
        }
        Map<String,String> subjectNameMap = examSubjectVos.stream().collect(Collectors.toMap(ExamSubjectVo::getSubjectId, ExamSubjectVo :: getSubjectName,(key1, key2)->key2));
        List<BaseAnalysisVo> baseAnalysisVoss = new ArrayList<>(enterpriseExamineeSubjectGradeVos.size());
        //按照科目分组
        Map<String,List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getSubjectId()));
        for (String key :subjectGradeMap.keySet()) {

            baseAnalysisVoss.add(bulidSubjectBaseAnalysisVo(key,subjectNameMap,scoreLineSettingSubVos,subjectGradeMap,enterpriseExamineeSubjectGradeVos));
        }
        return   baseAnalysisVoss;
    }

    private BaseAnalysisVo bulidSubjectBaseAnalysisVo(String key,Map<String,String> subjectNameMap, List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos,
                                            Map<String,List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap,List<EnterpriseExamineeSubjectGradeVo>  enterpriseExamineeSubjectGradeVos){
        BaseAnalysisVo vo = new BaseAnalysisVo();
        vo.setTypeName(subjectNameMap.get(key));
        if(CollectionUtils.isEmpty(subjectGradeMap.get(key))){
            defaultBaseAnalysisVo(vo);
        }else{
            int totalNum = subjectGradeMap.get(key).size();
            vo.setParticipantsNum(totalNum);
            BigDecimal maxScore = subjectGradeMap.get(key).stream().max(Comparator.comparing(EnterpriseExamineeSubjectGradeVo ::getScore)).get().getScore();
            BigDecimal minScore =  subjectGradeMap.get(key).stream().min(Comparator.comparing(EnterpriseExamineeSubjectGradeVo ::getScore)).get().getScore();
            vo.setMaxScore(maxScore);
            vo.setMinScore(minScore);
            BigDecimal allScore = subjectGradeMap.get(key).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal allUserTime = new BigDecimal(subjectGradeMap.get(key).stream().filter(e->null != e.getUseTime()).mapToLong(EnterpriseExamineeSubjectGradeVo::getUseTime).sum());

            vo.setAvgScore(allScore.divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP));
            vo.setUseTime(allUserTime.divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).longValue());
            vo.setUseTimeStr( DateUtils.getTimeStr(vo.getUseTime()) );
            vo.setUseTimeSec( DateUtils.getMinTimeStr(vo.getUseTime()));
            //区间则是排列占比
            if(CollectionUtils.isNotEmpty(scoreLineSettingSubVos)){
                List<DynamicColumnVo> dynamicColumnVos = new ArrayList<>(2);

                Map<String,List<EnterpriseExamineeSubjectGradeVo>> regionNameMap = enterpriseExamineeSubjectGradeVos.stream().filter(e->StringUtils.isNotEmpty(e.getRegionName())).collect(Collectors.groupingBy(c -> c.getRegionName()));
                 for (EnterpriseExamScoreLineSettingSubVo scoreLineSettingSubVo :scoreLineSettingSubVos){
                     DynamicColumnVo dynamicColumnVo = new DynamicColumnVo();
                    dynamicColumnVo.setColumnName(scoreLineSettingSubVo.getRegionName());
                    dynamicColumnVo.setColumnVal("0");
                    if(MapUtils.isNotEmpty(regionNameMap) && CollectionUtils.isNotEmpty(regionNameMap.get(scoreLineSettingSubVo.getRegionName()))){
                        dynamicColumnVo.setColumnVal(regionNameMap.get(scoreLineSettingSubVo.getRegionName()).size()+"");
                    }

                     dynamicColumnVos.add(dynamicColumnVo);
                    dynamicColumnVo = new DynamicColumnVo();
                    dynamicColumnVo.setColumnName( scoreLineSettingSubVo.getRegionName() + "占比（%）");
                    dynamicColumnVo.setColumnVal("0");
                    if(MapUtils.isNotEmpty(regionNameMap) && CollectionUtils.isNotEmpty(regionNameMap.get(scoreLineSettingSubVo.getRegionName()))){
                        dynamicColumnVo.setColumnVal(new BigDecimal(regionNameMap.get(scoreLineSettingSubVo.getRegionName()).size()*100).divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).toString());
                    }
                     dynamicColumnVos.add(dynamicColumnVo);
                }
                vo.setDynamicColumnVoList(dynamicColumnVos);
            }else{
                List<EnterpriseExamineeSubjectGradeVo> subjectGradeVos = subjectGradeMap.get(key).stream().filter(e->CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(e.getQualifiedStatus())).collect(Collectors.toList());
                //合格率=合格人数/总人数
                List<DynamicColumnVo> dynamicColumnVos = new ArrayList<>(2);

                DynamicColumnVo   dynamicColumnVo = new DynamicColumnVo();
                dynamicColumnVo.setColumnName("合格人数");
                dynamicColumnVo.setColumnVal(subjectGradeVos.size()+"");
                dynamicColumnVos.add(dynamicColumnVo);
                DynamicColumnVo dynamicColumnVo2 = new DynamicColumnVo();
                dynamicColumnVo2.setColumnName("合格率（%）");
                dynamicColumnVo2.setColumnVal(new BigDecimal(subjectGradeVos.size()*100).divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).toString());
                dynamicColumnVos.add(dynamicColumnVo2);
                vo.setDynamicColumnVoList(dynamicColumnVos);
            }
        }
        return  vo;
    }


    private List<EnterpriseExamineeSubjectGradeVo> getEnterpriseExamineeSubjectGradeVos(AnalysisVo analysisVo){
        QueryEnterpriseExamineeGradeVo queryExamineeGradeVo = new QueryEnterpriseExamineeGradeVo();
        queryExamineeGradeVo.setExamId(analysisVo.getExamId());
        if(null != analysisVo.getExamStartDate()){
            queryExamineeGradeVo.setBeginTime(DateUtils.formatDate(analysisVo.getExamStartDate(),DateUtils.YYYY_MM_DD_HH_MM_SS) );
        }
        if(null != analysisVo.getExamEndDate()){
            queryExamineeGradeVo.setEndTime(DateUtils.formatDate(analysisVo.getExamEndDate(),DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        long examineeBeginTime = System.currentTimeMillis();
        List<String> examineeIds = enterpriseExamineeInfoMapper.selectEnterprisExamineeIds(queryExamineeGradeVo);
        log.info("查询EnterpriseExamineeSubject数据的时间======================:{}",System.currentTimeMillis()-examineeBeginTime);
        if(CollectionUtils.isEmpty(examineeIds)){
            return  Collections.EMPTY_LIST;
        }
        long examineeGradeBeginTime = System.currentTimeMillis();
//        List<String> examineeIds = enterpriseExamineeInfos.stream().distinct().map(e -> e.getId()).collect(Collectors.toList());
        List<String> examIds = new ArrayList<>(1);
        examIds.add(analysisVo.getExamId());
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.
                selectExamineeSubjectGradeByExamIds(examIds.toArray(new String[examIds.size()]));
        log.info("查询EnterpriseExamineeSubjectGrade数据的时间======================:{}",System.currentTimeMillis()-examineeGradeBeginTime);

        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        Iterator<EnterpriseExamineeSubjectGradeVo> iterator = enterpriseExamineeSubjectGradeVos.iterator();
        while (iterator.hasNext()){
            EnterpriseExamineeSubjectGradeVo subjectGrade = iterator.next();
            if(!examineeIds.contains(subjectGrade.getExamineeId())){
                iterator.remove();
            }
        }
        return  enterpriseExamineeSubjectGradeVos;
    }

    @Override
    public  TableDataInfo selectBaseAnalysisList(AnalysisVo analysisVo)  {

        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){
            List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
            List<BaseAnalysisVo> baseAnalysisVos = getGroupExamBaseAnalysisVos(analysisVo,examIds);
            if(CollectionUtils.isEmpty(baseAnalysisVos)){
                return bulidTableDataInfo();
            }
            return resetDynamicColumnVoList(baseAnalysisVos);
        }else {
            List<BaseAnalysisVo> baseAnalysisVos = getCommonExamBaseAnalysisVos(analysisVo);
            if(CollectionUtils.isEmpty(baseAnalysisVos)){
                return bulidTableDataInfo();
            }
            return resetDynamicColumnVoList(baseAnalysisVos);

        }
    }


    private     List<BaseAnalysisVo> selectExportBaseAnalysisList(AnalysisVo analysisVo)  {

        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){
            List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
            return getGroupExamBaseAnalysisVos(analysisVo,examIds);

        }else {
            return getCommonExamBaseAnalysisVos(analysisVo);


        }
    }

    /**
     * 考试组（关联考试）
     * @param analysisVo
     * @return
     */
    private List<BaseAnalysisVo>  getGroupExamBaseAnalysisVos(AnalysisVo analysisVo,List<String> examIds){
        if(StringUtils.isNotEmpty(analysisVo.getRelationId())){
            examIds = new ArrayList<>(1);
            examIds.add(analysisVo.getRelationId());
        }
        List<ExamInfo> examInfos = examInfoMapper.selectExamInfoByIds(examIds.toArray(new String[examIds.size()]));
        if(CollectionUtils.isEmpty(examInfos)){
            return  Collections.EMPTY_LIST;
        }
//        Integer signNumber = examInfos.stream().filter(e->null != e.getSignNumber()).mapToInt(ExamInfo :: getSignNumber).sum();
        long examineeBeginTime = System.currentTimeMillis();
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getGroupEnterpriseExamineeInfos(examIds,analysisVo);
        log.info("查询GroupEnterpriseExaminee数据的时间======================:{}",System.currentTimeMillis()-examineeBeginTime);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  Collections.EMPTY_LIST;
        }
        long examineeGradeBeginTime = System.currentTimeMillis();
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getGroupEnterpriseExamineeSubjectGradeVos(examIds,enterpriseExamineeInfos,null);
        log.info("查询GroupEnterpriseExamineeGrade数据的时间======================:{}",System.currentTimeMillis()-examineeGradeBeginTime);

        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));

        for(EnterpriseExamineeInfo examineeInfo : enterpriseExamineeInfos){
            if(MapUtils.isEmpty(subjectGradeMap) || CollectionUtils.isEmpty(subjectGradeMap.get(examineeInfo.getId())) ){
                examineeInfo.setAllScore(BigDecimal.ZERO);
                continue;
            }
            examineeInfo.setAllScore(subjectGradeMap.get(examineeInfo.getId()).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos = null;
        if(CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())){
            scoreLineSettingSubVos= enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamId(
                    analysisVo.getRelationId(), CommonEnums.SCORE_LINE_DIMENSION_0.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }else {
            scoreLineSettingSubVos= enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamId(
                    analysisVo.getExamId(), CommonEnums.SCORE_LINE_DIMENSION_2.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        }
        List<BaseAnalysisVo> baseAnalysisVoss = new ArrayList<>(enterpriseExamineeSubjectGradeVos.size());
        Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap =  null;
        Map<String, String> dataMap = null;
        if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())) {
            List<String> sexs = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getSex())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(sexs)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getSex())).collect(Collectors.groupingBy(c -> c.getSex()));
            dataMap = sysDictDataService.selectDictDataMap("sys_user_sex", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())) {
            List<String> educations = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getEducation())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(educations)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getEducation())).collect(Collectors.groupingBy(c -> c.getEducation()));
            dataMap = sysDictDataService.selectDictDataMap("education", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())) {
            List<String> provinceCodes = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getProvinceCode())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(provinceCodes)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getProvinceCode())).collect(Collectors.groupingBy(c -> c.getProvinceCode()));
            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>(examInfos.size());
            for (ExamInfo examInfo :examInfos) {
                List<TaskCandidateAreaVO> tempTaskCandidateAreaVOList = areaService.getCandidateProvinceByTaskId(examInfo.getTaskId());
                if(CollectionUtils.isEmpty(tempTaskCandidateAreaVOList)){
                    continue;
                }
                taskCandidateAreaVOList.addAll(tempTaskCandidateAreaVOList);
            }
            dataMap =  taskCandidateAreaVOList.stream().collect(Collectors.toMap(TaskCandidateAreaVO::getAreaId, TaskCandidateAreaVO :: getName,(key1, key2)->key2));

        }else if (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())) {
            List<String> countryCodes = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getCityCode())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(countryCodes)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getCityCode())).collect(Collectors.groupingBy(c -> c.getCityCode()));
            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>(examInfos.size());
            for (ExamInfo examInfo :examInfos) {
                List<TaskCandidateAreaVO> tempTaskCandidateAreaVOList = areaService.getCandidateCityById(examInfo.getTaskId(), analysisVo.getProvinceCode());
                if(CollectionUtils.isEmpty(tempTaskCandidateAreaVOList)){
                    continue;
                }
                taskCandidateAreaVOList.addAll(tempTaskCandidateAreaVOList);
            }
             dataMap =  taskCandidateAreaVOList.stream().collect(Collectors.toMap(TaskCandidateAreaVO::getAreaId, TaskCandidateAreaVO :: getName,(key1, key2)->key2));
        } else if (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())) {
            List<String> tempRoomIds = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRoomId())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(tempRoomIds)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRoomId())).collect(Collectors.groupingBy(c -> c.getRoomId()));
            dataMap = new HashMap<>(examineeInfoMap.size());
            for (String key : examineeInfoMap.keySet()){
                if(CollectionUtils.isNotEmpty(examineeInfoMap.get(key))){
                    dataMap.put(key,examineeInfoMap.get(key).get(0).getRoomName());
                }
            }
        }else if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())) {
            List<String> examNameConfigIds =  examInfos.stream().distinct().map(e->e.getExamNameConfigId()).collect(Collectors.toList());
            List<ExamNameConfig> examNameConfigs = examNameConfigMapper.selectExamNameConfigByIds(examNameConfigIds.toArray(new String[examNameConfigIds.size()]));
            Map<String, String>  examNameMap = examNameConfigs.stream().collect(Collectors.toMap(ExamNameConfig::getId, ExamNameConfig :: getName,(key1, key2)->key2));;
            dataMap = new HashMap<>(examInfos.size());
            for (ExamInfo examInfo :examInfos){
                 dataMap.put(examInfo.getId(),examNameMap.get(examInfo.getExamNameConfigId()));
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getExamId()));

        }

        if(MapUtils.isEmpty(examineeInfoMap)){
            return  Collections.EMPTY_LIST;
        }
        if(MapUtils.isEmpty(dataMap)){
            return  Collections.EMPTY_LIST;
        }
        for (String key :examineeInfoMap.keySet()) {
            if(StringUtils.isEmpty(dataMap.get(key))){
                continue;
            }
            Integer formExam = ExamFormEnums.FORM_EXAM_GROUP.getCode();
            if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())){
                formExam =  ExamFormEnums.FORM_EXAM.getCode();
            }
            baseAnalysisVoss.add(bulidExamBaseAnalysisVo(key,dataMap,examineeInfoMap,scoreLineSettingSubVos, formExam));

        }
        return   baseAnalysisVoss;
    }

    /**
     * 普通考试
     * @param analysisVo
     * @return
     */
    private List<BaseAnalysisVo>  getCommonExamBaseAnalysisVos(AnalysisVo analysisVo){
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(analysisVo.getExamId());
        if(null == examInfo){
            return  Collections.EMPTY_LIST;
        }
        long examineeBeginTime = System.currentTimeMillis();
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getCommonEnterpriseExamineeInfos(analysisVo);
        log.info("查询EnterpriseExaminee数据的时间======================:{}",System.currentTimeMillis()-examineeBeginTime);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  Collections.EMPTY_LIST;
        }
        long examineeGradeBeginTime = System.currentTimeMillis();
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getCommonEnterpriseExamineeSubjectGradeVos(analysisVo.getExamId(),enterpriseExamineeInfos);
        log.info("查询EnterpriseExaminee数据的时间======================:{}",System.currentTimeMillis()-examineeGradeBeginTime);

        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));

        for(EnterpriseExamineeInfo examineeInfo : enterpriseExamineeInfos){
            if(MapUtils.isEmpty(subjectGradeMap) || CollectionUtils.isEmpty(subjectGradeMap.get(examineeInfo.getId())) ){
                examineeInfo.setAllScore(BigDecimal.ZERO);
                continue;
            }
            examineeInfo.setAllScore(subjectGradeMap.get(examineeInfo.getId()).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos = enterpriseExamScoreLineSettingSubMapper.selectRegionNameListByExamId(
                analysisVo.getExamId(), CommonEnums.SCORE_LINE_DIMENSION_0.getCode(), CommonEnums.SCORE_LINE_TYPE_2.getCode());
        List<BaseAnalysisVo> baseAnalysisVoss = new ArrayList<>(enterpriseExamineeSubjectGradeVos.size());
        Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap =  null;
        Map<String, String> dataMap = null;
        if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())) {
            List<String> sexs = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getSex())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(sexs)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getSex())).collect(Collectors.groupingBy(c -> c.getSex()));
            dataMap = sysDictDataService.selectDictDataMap("sys_user_sex", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())) {
            List<String> educations = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getEducation())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(educations)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getEducation())).collect(Collectors.groupingBy(c -> c.getEducation()));
            dataMap = sysDictDataService.selectDictDataMap("education", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())) {

            List<String> provinceCodes = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getProvinceCode())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(provinceCodes)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getProvinceCode())).collect(Collectors.groupingBy(c -> c.getProvinceCode()));
            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>();
            //合并科目特殊处理
           if(CommonEnums.EXAM_MERGE_TYPE_1.getCode().equals(String.valueOf(examInfo.getMergeType())) ){
               List<ExamInfoVo> groupExamInfos = getGroupExamInfoVos(analysisVo.getExamId());
               for (ExamInfoVo examInfoVo :groupExamInfos) {
                   List<TaskCandidateAreaVO> candidateAreaVOList = areaService.getCandidateProvinceByTaskId(examInfoVo.getTaskId());
                   if(CollectionUtils.isEmpty(candidateAreaVOList)){
                       continue;
                   }
                   taskCandidateAreaVOList.addAll(candidateAreaVOList);
               }

           }else {
               taskCandidateAreaVOList = areaService.getCandidateProvinceByTaskId(examInfo.getTaskId());
           }

            if(CollectionUtils.isNotEmpty(taskCandidateAreaVOList)){
                dataMap =  taskCandidateAreaVOList.stream().collect(Collectors.toMap(TaskCandidateAreaVO::getAreaId, TaskCandidateAreaVO :: getName,(key1, key2)->key2));
            }

        }else if (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())) {
            List<String> countryCodes = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getCityCode())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(countryCodes)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getCityCode())).collect(Collectors.groupingBy(c -> c.getCityCode()));

            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>();
            //合并科目特殊处理
            if(CommonEnums.EXAM_MERGE_TYPE_1.getCode().equals(String.valueOf(examInfo.getMergeType())) ){
                List<ExamInfoVo> groupExamInfos = getGroupExamInfoVos(analysisVo.getExamId());
                for (ExamInfoVo examInfoVo :groupExamInfos) {
                    List<TaskCandidateAreaVO> candidateAreaVOList = areaService.getCandidateCityById(examInfoVo.getTaskId(), analysisVo.getProvinceCode());
                    if(CollectionUtils.isEmpty(candidateAreaVOList)){
                        continue;
                    }
                    taskCandidateAreaVOList.addAll(candidateAreaVOList);
                }

            }else {
                taskCandidateAreaVOList = areaService.getCandidateCityById(examInfo.getTaskId(), analysisVo.getProvinceCode());
            }

            if(CollectionUtils.isNotEmpty(taskCandidateAreaVOList)){
                dataMap =  taskCandidateAreaVOList.stream().collect(Collectors.toMap(TaskCandidateAreaVO::getAreaId, TaskCandidateAreaVO :: getName,(key1, key2)->key2));
            }
        } else if (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())) {
            List<String> tempRoomIds = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRoomId())).map(e->e.getId()).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(tempRoomIds)){
                return  Collections.EMPTY_LIST;
            }
            examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRoomId())).collect(Collectors.groupingBy(c -> c.getRoomId()));
            dataMap = new HashMap<>(examineeInfoMap.size());
            for (String key : examineeInfoMap.keySet()){
                if(CollectionUtils.isNotEmpty(examineeInfoMap.get(key))){
                    dataMap.put(key,examineeInfoMap.get(key).get(0).getRoomName());
                }

            }
        }else if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())) {
            ExamNameConfig examNameConfig = examNameConfigMapper.selectExamNameConfigById(examInfo.getExamNameConfigId());
            dataMap = new HashMap<>(1);
            dataMap.put(examInfo.getId(),examNameConfig.getName());
            examineeInfoMap = enterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getExamId()));

        }

        if(MapUtils.isEmpty(examineeInfoMap)){
            return  Collections.EMPTY_LIST;
        }
        if(MapUtils.isEmpty(dataMap)){
            return  Collections.EMPTY_LIST;
        }
        for (String key :examineeInfoMap.keySet()) {
            if(StringUtils.isEmpty(dataMap.get(key))){
                continue;
            }
            baseAnalysisVoss.add(bulidExamBaseAnalysisVo(key,dataMap,examineeInfoMap,scoreLineSettingSubVos,
                    ExamFormEnums.FORM_EXAM.getCode()));
        }
        return   baseAnalysisVoss;
    }


    private BaseAnalysisVo  bulidExamBaseAnalysisVo(String key,Map<String, String> dataMap,
                         Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap,List<EnterpriseExamScoreLineSettingSubVo> scoreLineSettingSubVos
            , Integer examForm){
        BaseAnalysisVo vo = new BaseAnalysisVo();
        if(MapUtils.isNotEmpty(dataMap)){
            vo.setTypeName(dataMap.get(key));
        }
        if(CollectionUtils.isEmpty(examineeInfoMap.get(key))){
            defaultBaseAnalysisVo(vo);
        }else{
            List<EnterpriseExamineeInfo> allEnterpriseExamineeInfos = examineeInfoMap.get(key);
            Map<String,List<EnterpriseExamineeInfo>> tempExamineeInfoMap = allEnterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getIdcard()+c.getName()));
            List<EnterpriseExamineeInfo> enterpriseExamineeInfos = new ArrayList<>(tempExamineeInfoMap.size());
            for (String tempKey :tempExamineeInfoMap.keySet()) {
                List<EnterpriseExamineeInfo> examineeInfos = tempExamineeInfoMap.get(tempKey);
                EnterpriseExamineeInfo examineeInfo = examineeInfos.get(0);
                BigDecimal  score =  examineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                examineeInfo.setAllScore(score);
                enterpriseExamineeInfos.add(examineeInfo);
            }
            //按照name+idcard分组
            int totalNum = enterpriseExamineeInfos.size();
            vo.setParticipantsNum(totalNum);
            BigDecimal maxScore = enterpriseExamineeInfos.stream().max(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();
            BigDecimal minScore =  enterpriseExamineeInfos.stream().min(Comparator.comparing(EnterpriseExamineeInfo ::getAllScore)).get().getAllScore();
            vo.setMaxScore(maxScore);
            vo.setMinScore(minScore);
            BigDecimal allScore = enterpriseExamineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal allUserTime = new BigDecimal(enterpriseExamineeInfos.stream().filter(e->null != e.getUseTime()).mapToLong(EnterpriseExamineeInfo::getUseTime).sum());

            vo.setAvgScore(allScore.divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP));
            vo.setUseTime(allUserTime.divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).longValue());
            vo.setUseTimeStr( DateUtils.getTimeStr(vo.getUseTime()) );
            vo.setUseTimeSec( DateUtils.getMinTimeStr(vo.getUseTime()));
            //区间则是排列占比
            if(CollectionUtils.isNotEmpty(scoreLineSettingSubVos)){

                Map<String,List<EnterpriseExamineeInfo>> examineeRegionNameMap = null;
                if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examForm)){
                    examineeRegionNameMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getGroupRegionName())).collect(Collectors.groupingBy(c -> c.getGroupRegionName()));
                }else {
                    examineeRegionNameMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRegionName())).collect(Collectors.groupingBy(c -> c.getRegionName()));
                }
                List<DynamicColumnVo> dynamicColumnVos = new ArrayList<>(2);
                 for (EnterpriseExamScoreLineSettingSubVo scoreLineSettingSubVo :scoreLineSettingSubVos){
                     DynamicColumnVo dynamicColumnVo = new DynamicColumnVo();
                    dynamicColumnVo.setColumnName(scoreLineSettingSubVo.getRegionName());
                    dynamicColumnVo.setColumnVal("0");
                    if(MapUtils.isNotEmpty(examineeRegionNameMap) && CollectionUtils.isNotEmpty(examineeRegionNameMap.get(scoreLineSettingSubVo.getRegionName()))){
                        dynamicColumnVo.setColumnVal(examineeRegionNameMap.get(scoreLineSettingSubVo.getRegionName()).size()+"");
                    }
                     dynamicColumnVos.add(dynamicColumnVo);
                    dynamicColumnVo = new DynamicColumnVo();
                    dynamicColumnVo.setColumnName( scoreLineSettingSubVo.getRegionName() + "占比（%）");
                    dynamicColumnVo.setColumnVal("0");
                    if(MapUtils.isNotEmpty(examineeRegionNameMap) && CollectionUtils.isNotEmpty(examineeRegionNameMap.get(scoreLineSettingSubVo.getRegionName()))){
                        dynamicColumnVo.setColumnVal(new BigDecimal(examineeRegionNameMap.get(scoreLineSettingSubVo.getRegionName()).size()*100).divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).toString());
                    }
                     dynamicColumnVos.add(dynamicColumnVo);
                     vo.setDynamicColumnVoList(dynamicColumnVos);
                }
             }else{
                List<EnterpriseExamineeInfo> examineeInfos = null;
                if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examForm)){
                    examineeInfos = enterpriseExamineeInfos.stream().filter(e->CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(e.getGroupQualifiedStatus())).collect(Collectors.toList());
                }else {
                    examineeInfos = enterpriseExamineeInfos.stream().filter(e->CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(e.getQualifiedStatus())).collect(Collectors.toList());
                }
                //合格率=合格人数/总人数
                List<DynamicColumnVo> dynamicColumnVos = new ArrayList<>(2);
                DynamicColumnVo dynamicColumnVo = new DynamicColumnVo();
                dynamicColumnVo.setColumnName("合格人数");
                dynamicColumnVo.setColumnVal(examineeInfos.size()+"");
                dynamicColumnVos.add(dynamicColumnVo);
                dynamicColumnVo = new DynamicColumnVo();
                dynamicColumnVo.setColumnName("合格率（%）");
                dynamicColumnVo.setColumnVal(new BigDecimal(examineeInfos.size()*100).divide(new BigDecimal(totalNum),2, BigDecimal.ROUND_HALF_UP).toString());
                dynamicColumnVos.add(dynamicColumnVo);
                vo.setDynamicColumnVoList(dynamicColumnVos);
            }
        }

        return vo;

    }


    private void defaultBaseAnalysisVo( BaseAnalysisVo vo){
        vo.setParticipantsNum(0);
        List<DynamicColumnVo> dynamicColumnVos = new ArrayList<>(4);
        DynamicColumnVo dynamicColumnVo = new DynamicColumnVo();
        dynamicColumnVo.setColumnName("合格人数");
        dynamicColumnVo.setColumnVal("0");
        dynamicColumnVos.add(dynamicColumnVo);
        dynamicColumnVo = new DynamicColumnVo();
        dynamicColumnVo.setColumnName("合格率（%）");
        dynamicColumnVo.setColumnVal("0");
        dynamicColumnVos.add(dynamicColumnVo);
        vo.setDynamicColumnVoList(dynamicColumnVos);
        vo.setMaxScore(BigDecimal.ZERO);
        vo.setMinScore(BigDecimal.ZERO);
        vo.setAvgScore(BigDecimal.ZERO);
        vo.setUseTime(0L);
        vo.setUseTimeStr("0");
        vo.setUseTimeSec(BigDecimal.ZERO);
    }

    /**
     * 检查考试是否存在
     *
     * @param analysisVo
     * @return
     */
    private ExamInfo getExamInfo(AnalysisVo analysisVo) {
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(analysisVo.getExamId());
        if (examInfo == null || StringUtils.isEmpty(examInfo.getId())) {
            throw new CustomException("要查询的考试不存在");
        }
        return examInfo;
    }

    @Override
    public BlockAllAnalysisVo selectBlockSubjectAnalysisList(AnalysisVo analysisVo) {
        //考试组

        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){
            List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
            return bulidSubjectGroupBlockAllAnalysisVo(analysisVo,examIds);
        }else {
           return bulidSubjectCommonBlockAllAnalysisVo(analysisVo);
        }
    }

    private  BlockAllAnalysisVo bulidSubjectCommonBlockAllAnalysisVo(AnalysisVo analysisVo){
        BlockAllAnalysisVo blockAllAnalysisVo = new BlockAllAnalysisVo();
        //获取考试中考生的单科成绩信息
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = getCommonEnterpriseExamineeInfos(analysisVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  blockAllAnalysisVo;
        }
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getCommonEnterpriseExamineeSubjectGradeVos(analysisVo.getExamId(),enterpriseExamineeInfos);
        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  blockAllAnalysisVo;
        }
        //获取考试科目
        List<ExamSubjectVo> examSubjectInfoList = examSubjectInfoMapper.selecSubjectList(analysisVo.getExamId());
        //INFO 存在还没分段统计的情况和设置了分段统计的情况
        QueryWrapper<ExamScoreAnalysisLine> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ExamScoreAnalysisLine::getExamId, analysisVo.getExamId());
        ExamScoreAnalysisLine examScoreAnalysisLine = examScoreAnalysisLineLMapper.selectOne(queryWrapper);
        if (examScoreAnalysisLine == null || StringUtils.isEmpty(examScoreAnalysisLine.getId())) {

            //直接返回
            return bulidBlockAllAnalysisVo(examSubjectInfoList);

         }
        //如果是设置了分数段
        blockAllAnalysisVo.setMinScore(examScoreAnalysisLine.getMinScore());
        blockAllAnalysisVo.setMaxScore(examScoreAnalysisLine.getMaxScore());
        QueryWrapper<ExamScoreAnalysisBlockLine> BlockQuery = new QueryWrapper();
        BlockQuery.lambda().eq(ExamScoreAnalysisBlockLine::getLineId, examScoreAnalysisLine.getId()).orderByAsc(ExamScoreAnalysisBlockLine::getPoint);
        List<ExamScoreAnalysisBlockLine> examScoreAnalysisBlockLines = examScoreAnalysisBlockLineLMapper.selectList(BlockQuery);

        //区间 -> 科目  ->  人
        List<BlockAnalysisVo> blockAnalysisVoList = new ArrayList<>();
        for (ExamScoreAnalysisBlockLine examScoreAnalysisBlockLine : examScoreAnalysisBlockLines) {
            blockAnalysisVoList.add(bulidBlockAnalysisVo(  enterpriseExamineeSubjectGradeVos,  examScoreAnalysisBlockLine,   examSubjectInfoList));

         }
        blockAllAnalysisVo.setBlockDataList(blockAnalysisVoList);
        List<BlockDataAnalysisVo> typeDataList = new ArrayList<>();
        for (ExamSubjectVo examSubjectVo : examSubjectInfoList) {
            BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
            blockDataAnalysisVo.setName(examSubjectVo.getSubjectName());
            typeDataList.add(blockDataAnalysisVo);
        }
        blockAllAnalysisVo.setTypeDataList(typeDataList);
        return blockAllAnalysisVo;
    }

    private  int getAnalysisDataCount(List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos
            ,ExamScoreAnalysisBlockLine examScoreAnalysisBlockLine,ExamSubjectVo examSubjectVo){
        int count = 0;
        for (EnterpriseExamineeSubjectGradeVo examineeAnalysisData : enterpriseExamineeSubjectGradeVos) {
            if (examScoreAnalysisBlockLine.getLast().equals(CommonEnums.LAST_1.getCode())) {
                //这里处理下最后一个等于的情况
                if (examSubjectVo.getSubjectId().equals(examineeAnalysisData.getSubjectId()) &&
                        examineeAnalysisData.getScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getGreaterPoint())) > -1 &&
                        examineeAnalysisData.getScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getPoint())) < 1) {
                    count++;
                }
            } else {
                //这里处理下最后一个等于的情况
                if (examSubjectVo.getSubjectId().equals(examineeAnalysisData.getSubjectId()) &&
                        examineeAnalysisData.getScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getGreaterPoint())) > -1 &&
                        examineeAnalysisData.getScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getPoint())) == -1) {
                    count++;
                }
            }
        }
        return count;
    }


    private BlockAnalysisVo bulidBlockAnalysisVo(List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos
            ,ExamScoreAnalysisBlockLine examScoreAnalysisBlockLine, List<ExamSubjectVo> examSubjectInfoList){
        BlockAnalysisVo blockAnalysisVo = new BlockAnalysisVo();
        List<BlockDataAnalysisVo> blockDataAnalysisVoList = new ArrayList<>();
        for (ExamSubjectVo examSubjectVo : examSubjectInfoList) {
            BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();

            blockDataAnalysisVo.setName(examSubjectVo.getSubjectName());
            blockDataAnalysisVo.setCount(getAnalysisDataCount(enterpriseExamineeSubjectGradeVos,examScoreAnalysisBlockLine,examSubjectVo));
            blockDataAnalysisVoList.add(blockDataAnalysisVo);
        }
        blockAnalysisVo.setPoint(examScoreAnalysisBlockLine.getPoint());
        blockAnalysisVo.setDataList(blockDataAnalysisVoList);
        return blockAnalysisVo;
    }

    private  BlockAllAnalysisVo bulidSubjectGroupBlockAllAnalysisVo(AnalysisVo analysisVo,List<String> examIds){
        BlockAllAnalysisVo blockAllAnalysisVo = new BlockAllAnalysisVo();
        List<EnterpriseExamineeInfo>  enterpriseExamineeInfos = getGroupEnterpriseExamineeInfos(examIds,analysisVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  blockAllAnalysisVo;
        }
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos =  getGroupEnterpriseExamineeSubjectGradeVos(examIds,enterpriseExamineeInfos,null);
        //获取考试科目
        List<ExamSubjectVo> examSubjectInfoList = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds.toArray(new String[examIds.size()]));
        //INFO 存在还没分段统计的情况和设置了分段统计的情况
        QueryWrapper<ExamScoreAnalysisLine> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ExamScoreAnalysisLine::getExamId, analysisVo.getExamId());
        ExamScoreAnalysisLine examScoreAnalysisLine = examScoreAnalysisLineLMapper.selectOne(queryWrapper);
        if (examScoreAnalysisLine == null || StringUtils.isEmpty(examScoreAnalysisLine.getId())) {
            //直接返回
            return bulidBlockAllAnalysisVo(examSubjectInfoList);
        }
        //如果是设置了分数段
        blockAllAnalysisVo.setMinScore(examScoreAnalysisLine.getMinScore());
        blockAllAnalysisVo.setMaxScore(examScoreAnalysisLine.getMaxScore());
        QueryWrapper<ExamScoreAnalysisBlockLine> BlockQuery = new QueryWrapper();
        BlockQuery.lambda().eq(ExamScoreAnalysisBlockLine::getLineId, examScoreAnalysisLine.getId()).orderByAsc(ExamScoreAnalysisBlockLine::getPoint);
        List<ExamScoreAnalysisBlockLine> examScoreAnalysisBlockLines = examScoreAnalysisBlockLineLMapper.selectList(BlockQuery);

        //区间 -> 科目  ->  人
        List<BlockAnalysisVo> blockAnalysisVoList = new ArrayList<>();
        for (ExamScoreAnalysisBlockLine examScoreAnalysisBlockLine : examScoreAnalysisBlockLines) {

            blockAnalysisVoList.add(bulidBlockAnalysisVo(  enterpriseExamineeSubjectGradeVos,  examScoreAnalysisBlockLine,   examSubjectInfoList));
        }
        blockAllAnalysisVo.setBlockDataList(blockAnalysisVoList);
        List<BlockDataAnalysisVo> typeDataList = new ArrayList<>();
        for (ExamSubjectVo examSubjectVo : examSubjectInfoList) {
            BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
            blockDataAnalysisVo.setName(examSubjectVo.getSubjectName());
            typeDataList.add(blockDataAnalysisVo);
        }
        blockAllAnalysisVo.setTypeDataList(typeDataList);
        return blockAllAnalysisVo;
    }


    private BlockAllAnalysisVo bulidBlockAllAnalysisVo(List<ExamSubjectVo> examSubjectInfoList){
        BlockAllAnalysisVo blockAllAnalysisVo = new BlockAllAnalysisVo();
        //直接返回
        List<BlockDataAnalysisVo> typeDataList = new ArrayList<>();
        for (ExamSubjectVo examSubjectVo : examSubjectInfoList) {
            BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
            blockDataAnalysisVo.setName(examSubjectVo.getSubjectName());
            typeDataList.add(blockDataAnalysisVo);
        }
        blockAllAnalysisVo.setTypeDataList(typeDataList);
        List<BlockAnalysisVo> blockAnalysisVoList = new ArrayList<>();
        blockAllAnalysisVo.setBlockDataList(blockAnalysisVoList);
        blockAllAnalysisVo.setMaxScore(100);
        blockAllAnalysisVo.setMinScore(0);
        return  blockAllAnalysisVo;
    }

    private List<EnterpriseExamineeInfo>  getGroupEnterpriseExamineeInfos(List<String> examIds,AnalysisVo analysisVo){
        QueryEnterpriseExamineeGradeVo queryExamineeGradeVo = new QueryEnterpriseExamineeGradeVo();
        queryExamineeGradeVo.setExamIds(examIds.toArray(new String[examIds.size()]));
        if(null != analysisVo.getExamStartDate()){
            queryExamineeGradeVo.setBeginTime(DateUtils.formatDate(analysisVo.getExamStartDate(),DateUtils.YYYY_MM_DD_HH_MM_SS) );
        }
        if(null != analysisVo.getExamEndDate()){
            queryExamineeGradeVo.setEndTime(DateUtils.formatDate(analysisVo.getExamEndDate(),DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeAnalysisInfoList(queryExamineeGradeVo);
        return  enterpriseExamineeInfos;
    }

    private  List<EnterpriseExamineeSubjectGradeVo> getGroupEnterpriseExamineeSubjectGradeVos(List<String> examIds,List<EnterpriseExamineeInfo> enterpriseExamineeInfos,String subjectId){
        List<String>  examineeIds = enterpriseExamineeInfos.stream().distinct().map(e -> e.getId()).collect(Collectors.toList());
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.
                selectExamineeSubjectGradeAnalysisByExamIds(examIds.toArray(new String[examIds.size()]));

        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        Iterator<EnterpriseExamineeSubjectGradeVo> iterator = enterpriseExamineeSubjectGradeVos.iterator();
        while (iterator.hasNext()){
            EnterpriseExamineeSubjectGradeVo subjectGrade = iterator.next();
            if(!examineeIds.contains(subjectGrade.getExamineeId())){
                iterator.remove();
            }
            if(StringUtils.isNotEmpty(subjectId) && !subjectId.equals(subjectGrade.getSubjectId())){
                iterator.remove();
            }
        }
        return enterpriseExamineeSubjectGradeVos;
    }

    private List<EnterpriseExamineeInfo>  getCommonEnterpriseExamineeInfos(AnalysisVo analysisVo){
        QueryEnterpriseExamineeGradeVo queryExamineeGradeVo = new QueryEnterpriseExamineeGradeVo();
        queryExamineeGradeVo.setExamId(analysisVo.getExamId());
        if(null != analysisVo.getExamStartDate()){
            queryExamineeGradeVo.setBeginTime(DateUtils.formatDate(analysisVo.getExamStartDate(),DateUtils.YYYY_MM_DD_HH_MM_SS) );
        }
        if(null != analysisVo.getExamEndDate()){
            queryExamineeGradeVo.setEndTime(DateUtils.formatDate(analysisVo.getExamEndDate(),DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeAnalysisInfoList(queryExamineeGradeVo);
        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
            return  Collections.EMPTY_LIST;
        }
        return  enterpriseExamineeInfos;
    }

    private  List<EnterpriseExamineeSubjectGradeVo> getCommonEnterpriseExamineeSubjectGradeVos(String examId,List<EnterpriseExamineeInfo> enterpriseExamineeInfos){
        List<String> examineeIds = enterpriseExamineeInfos.stream().distinct().map(e -> e.getId()).collect(Collectors.toList());
        List<String> examIds = new ArrayList<>(1);
        examIds.add(examId);
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.
                selectExamineeSubjectGradeAnalysisByExamIds(examIds.toArray(new String[examIds.size()]));
        if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
            return  Collections.EMPTY_LIST;
        }
        Iterator<EnterpriseExamineeSubjectGradeVo> iterator = enterpriseExamineeSubjectGradeVos.iterator();
        while (iterator.hasNext()){
            EnterpriseExamineeSubjectGradeVo subjectGrade = iterator.next();
            if(!examineeIds.contains(subjectGrade.getExamineeId())){
                iterator.remove();
            }
        }
        return enterpriseExamineeSubjectGradeVos;
    }

    @Override
    public BlockAllAnalysisVo selectBlockAnalysisList(AnalysisVo analysisVo) {
        ExamInfo examInfo = getExamInfo(analysisVo);
        BlockAllAnalysisVo blockAllAnalysisVo = new BlockAllAnalysisVo();
        List<EnterpriseExamineeInfo> allEnterpriseExamineeInfos = null;
        List<EnterpriseExamineeSubjectGradeVo> enterpriseExamineeSubjectGradeVos = null;
        //获取所有数据
        //获取考试中考生的单科成绩信息
        List<ExamInfoVo> examInfoVos = getExamInfoVos(analysisVo.getExamId());
        if(CollectionUtils.isNotEmpty(examInfoVos)){
            List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
            allEnterpriseExamineeInfos = getGroupEnterpriseExamineeInfos(examIds,analysisVo);
            if(CollectionUtils.isEmpty(allEnterpriseExamineeInfos)){
                return  blockAllAnalysisVo;
            }
            enterpriseExamineeSubjectGradeVos =  getGroupEnterpriseExamineeSubjectGradeVos(examIds,allEnterpriseExamineeInfos,null);

        }else {
            allEnterpriseExamineeInfos =  getCommonEnterpriseExamineeInfos(analysisVo);
            if(CollectionUtils.isEmpty(allEnterpriseExamineeInfos)){
                return  blockAllAnalysisVo;
            }
            enterpriseExamineeSubjectGradeVos = getCommonEnterpriseExamineeSubjectGradeVos(analysisVo.getExamId(),allEnterpriseExamineeInfos);
            if(CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)){
                return  blockAllAnalysisVo;
            }
        }

        Map<String, List<EnterpriseExamineeSubjectGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));
        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = new ArrayList<>(allEnterpriseExamineeInfos.size());
        Map<String,List<EnterpriseExamineeInfo>> tempExamineeInfoMap = null;
        if(CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())){
             tempExamineeInfoMap = allEnterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getExamId()+c.getIdcard()+c.getName()));
        }else {
             tempExamineeInfoMap = allEnterpriseExamineeInfos.stream().collect(Collectors.groupingBy(c -> c.getIdcard()+c.getName()));
        }
        if(MapUtils.isEmpty(tempExamineeInfoMap)){
            return  blockAllAnalysisVo;
        }
        for (String tempKey :tempExamineeInfoMap.keySet()) {
            List<EnterpriseExamineeInfo> examineeInfos = tempExamineeInfoMap.get(tempKey);
            for(EnterpriseExamineeInfo examineeInfo : examineeInfos){
                if(MapUtils.isEmpty(subjectGradeMap) || CollectionUtils.isEmpty(subjectGradeMap.get(examineeInfo.getId())) ){
                    examineeInfo.setAllScore(BigDecimal.ZERO);
                    continue;
                }
                examineeInfo.setAllScore(subjectGradeMap.get(examineeInfo.getId()).stream().filter(e->null != e.getScore()).map(EnterpriseExamineeSubjectGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
            EnterpriseExamineeInfo examineeInfo = examineeInfos.get(0);
            BigDecimal  score =  examineeInfos.stream().filter(e->null != e.getAllScore()).map(EnterpriseExamineeInfo::getAllScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            examineeInfo.setAllScore(score);
            enterpriseExamineeInfos.add(examineeInfo);
        }
        //获取所有类型
        Map<String, String> dataMap = null;
        if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())) {
            dataMap = sysDictDataService.selectDictDataMap("sys_user_sex", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())) {
            dataMap = sysDictDataService.selectDictDataMap("education", "K");
        } else if (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())) {
            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>();
            List<ExamInfoVo> groupExamInfos = getGroupExamInfoVos(analysisVo.getExamId());
            for (ExamInfoVo exam  :groupExamInfos) {
                List<TaskCandidateAreaVO> tempTaskCandidateAreaVOs = areaService.getCandidateProvinceByTaskId(exam.getTaskId());
                if(CollectionUtils.isEmpty(tempTaskCandidateAreaVOs)){
                    continue;
                }
                taskCandidateAreaVOList.addAll(tempTaskCandidateAreaVOs);
            }
            if (taskCandidateAreaVOList == null || taskCandidateAreaVOList.size() < 1) {
                return blockAllAnalysisVo;
            }
            dataMap = new HashMap<>();
            Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getProvinceCode())).collect(Collectors.groupingBy(c -> c.getProvinceCode()));
            for (TaskCandidateAreaVO taskCandidateAreaVO : taskCandidateAreaVOList) {

                if(MapUtils.isEmpty(examineeInfoMap) || null == examineeInfoMap.get(taskCandidateAreaVO.getAreaId())){
                    continue;
                }
                dataMap.put(taskCandidateAreaVO.getAreaId(), taskCandidateAreaVO.getName());
            }
        } else if (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())) {
            List<TaskCandidateAreaVO> taskCandidateAreaVOList = new ArrayList<>();
            List<ExamInfoVo> groupExamInfos = getGroupExamInfoVos(analysisVo.getExamId());
            for (ExamInfoVo exam  :groupExamInfos) {
                List<TaskCandidateAreaVO> tempTaskCandidateAreaVOs = areaService.getCandidateCityById(exam.getTaskId(), analysisVo.getProvinceCode());
                if(CollectionUtils.isEmpty(tempTaskCandidateAreaVOs)){
                    continue;
                }
                taskCandidateAreaVOList.addAll(tempTaskCandidateAreaVOs);
            }
            if (taskCandidateAreaVOList == null || taskCandidateAreaVOList.size() < 1) {
                return blockAllAnalysisVo;
            }
            Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getCityCode())).collect(Collectors.groupingBy(c -> c.getCityCode()));
            dataMap = new HashMap<>();
            for (TaskCandidateAreaVO taskCandidateAreaVO : taskCandidateAreaVOList) {
                if(MapUtils.isEmpty(examineeInfoMap) || null == examineeInfoMap.get(taskCandidateAreaVO.getAreaId())){
                    continue;
                }
                dataMap.put(taskCandidateAreaVO.getAreaId(), taskCandidateAreaVO.getName());
            }
        } else if (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())) {
           Map<String,List<EnterpriseExamineeInfo>> examineeInfoMap = enterpriseExamineeInfos.stream().filter(e->StringUtils.isNotEmpty(e.getRoomId())).collect(Collectors.groupingBy(c -> c.getRoomId()));
            dataMap = new HashMap<>(examineeInfoMap.size());
            for (String key : examineeInfoMap.keySet()){
                if(CollectionUtils.isNotEmpty(examineeInfoMap.get(key))){
                    dataMap.put(key,examineeInfoMap.get(key).get(0).getRoomName());
                }
            }
        }else if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())) {
            if(CollectionUtils.isNotEmpty(examInfoVos)){
                List<String> examIds = examInfoVos.stream().distinct().map(e->e.getId()).collect(Collectors.toList());
                List<ExamInfo> examInfos = examInfoMapper.selectExamInfoByIds(examIds.toArray(new String[examIds.size()]));
                List<String> examNameConfigIds =  examInfos.stream().distinct().map(e->e.getExamNameConfigId()).collect(Collectors.toList());
                List<ExamNameConfig> examNameConfigs = examNameConfigMapper.selectExamNameConfigByIds(examNameConfigIds.toArray(new String[examNameConfigIds.size()]));
                Map<String, String>  examNameMap = examNameConfigs.stream().collect(Collectors.toMap(ExamNameConfig::getId, ExamNameConfig :: getName,(key1, key2)->key2));;
                dataMap = new HashMap<>(examInfos.size());
                for (ExamInfo exam:examInfos) {
                    dataMap.put(exam.getId(),examNameMap.get(exam.getExamNameConfigId()));
                }
            }else {
                ExamNameConfig examNameConfig = examNameConfigMapper.selectExamNameConfigById(examInfo.getExamNameConfigId());
                dataMap = new HashMap<>(1);
                dataMap.put(examInfo.getId(),examNameConfig.getName());
            }
        }

        //INFO 存没分段统计
        QueryWrapper<ExamScoreAnalysisLine> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ExamScoreAnalysisLine::getExamId, analysisVo.getExamId());
        ExamScoreAnalysisLine examScoreAnalysisLine = examScoreAnalysisLineLMapper.selectOne(queryWrapper);
        if (examScoreAnalysisLine == null || StringUtils.isEmpty(examScoreAnalysisLine.getId())) {

            List<BlockDataAnalysisVo> typeDataList = new ArrayList<>();
            Iterator<Map.Entry<String, String>> entries = dataMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, String> entry = entries.next();
                String k = entry.getKey();
                String v = entry.getValue();
                BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
                blockDataAnalysisVo.setName(v);
                typeDataList.add(blockDataAnalysisVo);
            }
            blockAllAnalysisVo.setTypeDataList(typeDataList);
            List<BlockAnalysisVo> blockAnalysisVoList = new ArrayList<>();
            blockAllAnalysisVo.setBlockDataList(blockAnalysisVoList);
            blockAllAnalysisVo.setMaxScore(100);
            blockAllAnalysisVo.setMinScore(0);
            return blockAllAnalysisVo;
        }

        //INFO 设置了分数段统计
        blockAllAnalysisVo.setMinScore(examScoreAnalysisLine.getMinScore());
        blockAllAnalysisVo.setMaxScore(examScoreAnalysisLine.getMaxScore());
        QueryWrapper<ExamScoreAnalysisBlockLine> BlockQuery = new QueryWrapper();
        BlockQuery.lambda().eq(ExamScoreAnalysisBlockLine::getLineId, examScoreAnalysisLine.getId()).orderByAsc(ExamScoreAnalysisBlockLine::getPoint);
        List<ExamScoreAnalysisBlockLine> examScoreAnalysisBlockLines = examScoreAnalysisBlockLineLMapper.selectList(BlockQuery);

        //区间 -> 动态列  ->  人
        List<BlockAnalysisVo> blockAnalysisVoList = new ArrayList<>();
        for (ExamScoreAnalysisBlockLine examScoreAnalysisBlockLine : examScoreAnalysisBlockLines) {
            BlockAnalysisVo blockAnalysisVo = new BlockAnalysisVo();
            List<BlockDataAnalysisVo> blockDataAnalysisVoList = new ArrayList<>();
            Iterator<Map.Entry<String, String>> entries = dataMap.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, String> entry = entries.next();
                String k = entry.getKey();
                String v = entry.getValue();
                BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
                int count = 0;
                blockDataAnalysisVo.setName(v);
                for (EnterpriseExamineeInfo examineeAnalysisData : enterpriseExamineeInfos) {
                    if(null == examineeAnalysisData.getAllScore()){
                        continue;
                    }
                    if (examScoreAnalysisBlockLine.getLast().equals(CommonEnums.LAST_1.getCode())) {
                        //这里处理下最后一个等于的情况
                        boolean flag = (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getSex()))
                                || (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getEducation()))
                                || (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getProvinceCode()))
                                || (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getCityCode()))
                                || (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getRoomId()))
                                || (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getExamId()));
                        if (flag && examineeAnalysisData.getAllScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getGreaterPoint())) > -1
                                && examineeAnalysisData.getAllScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getPoint())) < 1) {
                            count++;
                        }
                    } else {
                        //这里处理下最后一个等于的情况
                        boolean flag = (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getSex()))
                                || (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getEducation()))
                                || (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getProvinceCode()))
                                || (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getCityCode()))
                                || (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getRoomId()))
                                || (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType()) && k.equals(examineeAnalysisData.getExamId()));
                        if (flag && examineeAnalysisData.getAllScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getGreaterPoint())) > -1
                                && examineeAnalysisData.getAllScore().compareTo(new BigDecimal(examScoreAnalysisBlockLine.getPoint())) == -1) {
                            count++;
                        }
                    }
                }
                blockDataAnalysisVo.setCount(count);
                blockDataAnalysisVoList.add(blockDataAnalysisVo);
            }
            blockAnalysisVo.setPoint(examScoreAnalysisBlockLine.getPoint());
            blockAnalysisVo.setDataList(blockDataAnalysisVoList);
            blockAnalysisVoList.add(blockAnalysisVo);
        }
        blockAllAnalysisVo.setBlockDataList(blockAnalysisVoList);
        List<BlockDataAnalysisVo> typeDataList = new ArrayList<>();
        Iterator<Map.Entry<String, String>> entries = dataMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            String k = entry.getKey();
            String v = entry.getValue();
            BlockDataAnalysisVo blockDataAnalysisVo = new BlockDataAnalysisVo();
            blockDataAnalysisVo.setName(v);
            typeDataList.add(blockDataAnalysisVo);
        }
        blockAllAnalysisVo.setTypeDataList(typeDataList);
        return blockAllAnalysisVo;
    }

    @Override
    public XSSFWorkbook exportAnalysisList(AnalysisVo analysisVo, PageDomain pageDomain) {
        XSSFWorkbook xssfWorkbook = null;
        if (CommonEnums.ANALYSIS_TYPE_SBUJECT.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportSubjectAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, rows.get(0).getTypeName());
        } else if (CommonEnums.ANALYSIS_TYPE_SEX.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_SEX_ANALYSIS_FILE_NAME.getDesc());
        } else if (CommonEnums.ANALYSIS_TYPE_EDUCATION.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_EDUCATION_ANALYSIS_FILE_NAME.getDesc());
        } else if (CommonEnums.ANALYSIS_TYPE_PROVINCE.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_PROVINCE_ANALYSIS_FILE_NAME.getDesc());
        } else if (CommonEnums.ANALYSIS_TYPE_CITY.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_CITY_ANALYSIS_FILE_NAME.getDesc());
        } else if (CommonEnums.ANALYSIS_TYPE_EXAMROOM.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_EXAMROOM_ANALYSIS_FILE_NAME.getDesc());
        } else if (CommonEnums.ANALYSIS_TYPE_EXAM.getCode().equals(analysisVo.getType())) {
            List<BaseAnalysisVo> rows = this.selectExportBaseAnalysisList(analysisVo);
            if(CollectionUtils.isEmpty(rows)){
                return null;
            }
            xssfWorkbook = AnalysisDataExportUtil.exportBaseAnalysisExcel(rows, analysisVo, CommonEnums.EXPORT_EXAM_ANALYSIS_FILE_NAME.getDesc());
        }

        return xssfWorkbook;
    }

    @Override
    public CheckExamSubjectVo checkExamSubject(String examId) {
        CheckExamSubjectVo checkExamSubjectVo = new CheckExamSubjectVo();
        //考试组
        ExamInfoVo examInfoVo = examInfoMapper.selectExamInfoByExamId(examId);
        if (examInfoVo == null || StringUtils.isEmpty(examInfoVo.getId())) {
            return  null;
        }
        //考试组
        List<String> examIds = new ArrayList<>();
        if(ExamFormEnums.FORM_EXAM_GROUP.getCode().equals(examInfoVo.getExamForm())){
            List<EnterpriseExamScoreLineSetting> settingList = new ArrayList<>();
            //关联考试
            List<ExamInfoVo> examInfoVos = getExamInfoVos(examId);
            //合并考试
            if(CollectionUtils.isNotEmpty(examInfoVos) && examInfoVos.size()>1){
                for (ExamInfoVo examVo :examInfoVos) {
                    examIds.add(examVo.getId());
                    settingList.addAll(getEnterpriseExamScoreLineSettings(examVo.getId(), CommonEnums.SCORE_LINE_TYPE_2.getCode(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode()));
                }
            }else {
                //合并科目
                examIds.add(examId);
                settingList.addAll(getEnterpriseExamScoreLineSettings(examId, CommonEnums.SCORE_LINE_TYPE_2.getCode(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode()));
            }

            if (settingList.size() > 0 && CollectionUtils.isNotEmpty(examIds)) {
                checkExamSubjectVo.setExit(true);
                List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectListByExamIds(examIds.toArray(new String[examIds.size()]));
                checkExamSubjectVo.setSubjectList(examSubjectVos);
            }
        }else {
            //判断考生考试下的科目是否设置区间分数段
            List<EnterpriseExamScoreLineSetting> settingList = getEnterpriseExamScoreLineSettings(examId, CommonEnums.SCORE_LINE_TYPE_2.getCode(), CommonEnums.SCORE_LINE_DIMENSION_1.getCode());
            //如果单科设置了区间分数线，那么就要前端选择科目进行展示
            if (settingList.size() > 0) {
                checkExamSubjectVo.setExit(true);
                List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selecSubjectList(examId);
                checkExamSubjectVo.setSubjectList(examSubjectVos);
            }
        }

        return checkExamSubjectVo;
    }

    /**
     * 根据考试维度和考试的类型获取考试下的分数线
     *
     * @param examId
     * @param type
     * @param dimension
     * @return
     */
    private List<EnterpriseExamScoreLineSetting> getEnterpriseExamScoreLineSettings(String examId, String type, String dimension) {
        EnterpriseExamScoreLineSetting enterpriseExamScoreLineSetting = new EnterpriseExamScoreLineSetting();
        enterpriseExamScoreLineSetting.setExamId(examId);
        enterpriseExamScoreLineSetting.setComposite(type);
        enterpriseExamScoreLineSetting.setDimension(dimension);
        List<EnterpriseExamScoreLineSetting> settingList = enterpriseExamScoreLineSettingMapper.selectEnterpriseExamScoreLineSettingList(enterpriseExamScoreLineSetting);
        return settingList;
    }


    private  List<ExamInfoVo>  getExamInfoVos(String examId){
        List<ExamInfoVo> examInfoVos = null;
        ExamInfo examInfo  = examInfoMapper.selectExamInfoById(examId);
        if(null != examInfo && null != examInfo.getMergeType() &&
                CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))){
            Map<String,Object> parms = new HashMap<>();
            parms.put("relationId",examId);
            examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
        }

        return examInfoVos;
    }


    private  List<ExamInfoVo>  getGroupExamInfoVos(String examId){
        List<ExamInfoVo> examInfoVos = null;
        ExamInfo examInfo  = examInfoMapper.selectExamInfoById(examId);
        if(null != examInfo ){
            Map<String,Object> parms = new HashMap<>();
            parms.put("relationId",examId);
            examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
        }

        return examInfoVos;
    }

}
